/**
 * @description  分页获取商品列表
 * @author unhejing (成都-敬宇杰)
 * @date 2020-02-21 上午10:52:07
 */
'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event:' + event)
	if(!event.page){
		event.page = 1;
	}
	if(!event.pageSize){
		event.pageSize = 10;
	}
	console.log('event.page:' + event.page+" event.pageSize:"+event.pageSize+" event.searchKey:"+event.searchKey)
	// 设置请求参数
	const {
		searchKey, //搜索关键词
		page,
		pageSize
	} = event
	const collection = db.collection('product') // 获取表'product'的集合对象
	let res;
	if (!!searchKey) {
		console.log("关键字查询:"+searchKey)
		const dbCmd = db.command;
		res = await collection.where(
			dbCmd.or({
				product_code: new RegExp(searchKey)
			}, {
				product_name: new RegExp(searchKey)
			})
		).orderBy("create_time", "desc").skip((page - 1) * pageSize).limit(pageSize).get();
	} else {
		res = await collection.orderBy("create_time", "desc").skip((page - 1) * pageSize).limit(pageSize).get();
	}
	console.log("商品响应数据:"+JSON.stringify(res))
	if (!res.data || res.data.length === 0) {
		return {
			success: false,
			code: -1,
			msg: '暂无数据'
		}
	}
	if (res.id || res.affectedDocs >= 1) {
		return {
			success: true,
			code: 0,
			msg: '成功',
			data: res.data
		}
	}
	return {
		success: false,
		code: -1,
		msg: '服务器内部错误'
	}
};
